package com.vehicle.controller;

import com.vehicle.bean.DataGridView;
import com.vehicle.bean.ResultDto;
import com.vehicle.pojo.Permission;
import com.vehicle.pojo.Role;
import com.vehicle.realm.VehiclesRealm;
import com.vehicle.service.PermissionService;
import com.vehicle.service.RoleService;
import com.vehicle.util.ReamlUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    private Logger logger=Logger.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping("/roles")
    public DataGridView list(Role role){
        return roleService.findRoleByPage(role);
    }

    @ResponseBody
    @RequestMapping("/assignPer")
    public ResultDto assignPer(){
        ResultDto resultDto=new ResultDto();
        List<Permission> permissions = permissionService.findPermissions();
        try {
            resultDto.setCode(200);
            resultDto.setMsg("成功");
            resultDto.setData(permissions);
        } catch (Exception e) {
            resultDto.setCode(-200);
            resultDto.setMsg("失败");
            e.printStackTrace();
        }
        return resultDto;
    }
    @RequestMapping("/getChecked")
    @ResponseBody
    public List<Integer> getChecked(Integer rid){
        List<Integer> pids = permissionService.findPids(rid);
        return pids;
    }

    //更改权限
    @ResponseBody
    @RequestMapping("/assignPermission")
    public ResultDto assignPermission(@RequestParam("rid") Integer rid,@RequestParam("pids[]") Integer[] pids){
        ResultDto resultDto=new ResultDto();
        try {
            roleService.assignPermission(rid,pids);
            //清理缓存
            ReamlUtil.clearCache();
            resultDto.setMsg("更改成功");
            resultDto.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            resultDto.setMsg("更改失败");
            resultDto.setCode(-200);
        }
        return resultDto;
    }
    @ResponseBody
    @RequestMapping("/addRole")
    public ResultDto addRole(Role role){
        ResultDto resultDto=new ResultDto();
        try {
            roleService.addRole(role);
            resultDto.setCode(200);
            resultDto.setMsg("增加成功");
        } catch (Exception e) {
            resultDto.setCode(-200);
            resultDto.setMsg("增加失败");
            e.printStackTrace();
        }

        return  resultDto;
    }
}
